package com.pet.server.ext.action.user;

import java.util.Date;

import com.pet.server.ext.ActionBase;
import com.pet.server.ext.ApiError;
import com.pet.server.ext.Result;
import com.pet.server.ext.data.UserInfo;
import com.pet.server.ext.data.VerificationCode;
import com.pet.server.ext.service.SystemService;
import com.pet.server.ext.service.UserService;
import com.pet.server.ext.util.DateUtil;
import com.pet.server.ext.util.Parameters;
import com.pet.server.ext.util.StringUtil;
public class Updatepwd extends ActionBase{
	
	public String phone_number,password;
	public String code;
	public VerificationCode vcode = null;
	public Updatepwd(){
		 needCheckAuth =false;
	}
	
	@Override
	public void initParameters(Parameters params) throws ApiError {	
		phone_number = params.getFieldValue("phone_number");
		password = params.getFieldValue("password");
		code = params.getFieldValue("code");
		if(StringUtil.isEmpty(phone_number,password)){
			throw ApiError.Type.INVALID_PARAM.toException();
		}

		SystemService systemService = new SystemService();
	    vcode = systemService.findVerification(phone_number);
	    if(null==vcode || !StringUtil.equals(vcode.getVerification_code(), code)){
	    	throw ApiError.Type.LOGIC_ERROR.toException("验证码错误!");
	    }
	    long distance = DateUtil.getMinByTwoDate(vcode.getSend_time(), new Date());
	    if(distance>30){
	    	throw ApiError.Type.LOGIC_ERROR.toException("验证码30分钟有效!");
	    }
	    systemService.updateVerification(vcode.id);
	}
	
	@Override
	public Result invokeService() throws ApiError {
		UserService userService = new UserService();
		UserInfo user = userService.findUserInfoByUserName(phone_number);
		if(null==user){
		   throw ApiError.Type.LOGIC_ERROR.toException();	
		}
		System.out.println("================="+phone_number+"  "+password);
		
		Integer i = userService.updateUserPassword(phone_number, password);
        data.put("message", i);
		Result result = new Result();
		result.put("data", data);
	    return result;
	}
	
	
}
